package com.youlu.campus.web.client;


import com.alibaba.fastjson.JSON;
import com.youlu.campus.common.exception.BusinessException;

import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.VO.req.WechatH5CodeReqVO;
import com.youlu.campus.service.platform.PlatformConfigService;
import com.youlu.campus.web.common.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class QQTokenService {

    @Autowired
    private QQTokenClient qqTokenClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private PlatformConfigService platformConfigService;

   // private final String ACCESS_TOKEN = "campus:qq:appId:access_token:%s";

    private final String FORMAT_JSON = "json";

    private final String QQ_URL = "https://graph.qq.com";

    private final String AUTHORIZE_URL = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=%s&state=test&scope=get_user_info" +
            "&redirect_uri=%s";

    public QQUserInfoResult getUserInfo(String code, String appId,String appSecret,String activityId,Integer type) throws IOException, URISyntaxException {
        log.info("通过 appId -> {},code - > {},appSecret - >{} 获取用户信息",appId,code,appSecret);
        String activityThemeColor = getActivityColor(activityId);
        String redirectUri = platformConfigService.getQQBizFrontDomain() + "/h5/index.html?#/pages/user-login?activityId=" + activityId + "&appId" + "=" + appId + "&type=" + type + "&theme=" + activityThemeColor+"&platform=qq-h5&authorizeMode=qq";
        Map<String,Object> paramMap = new HashMap<>(7);
        paramMap.put("grant_type","authorization_code");
        paramMap.put("client_id",appId);
        paramMap.put("client_secret",appSecret);
        paramMap.put("code",code);
        paramMap.put("scope","get_user_info");
        paramMap.put("fmt",FORMAT_JSON);
        paramMap.put("redirect_uri",redirectUri);
        log.info(" 获取 qq redirectUri - >{} request param - > {} ", redirectUri,JSON.toJSONString(paramMap));
        String accessTokenResult = HttpClientUtil.get(QQ_URL+"/oauth2.0/token", paramMap, null, 3000, "utf8", 3, true);
        log.info(" 获取 qq appId - >{} access_token result{} ", appId,accessTokenResult);
        QQResult qqResult = JSON.parseObject(accessTokenResult, QQResult.class);
        if(qqResult.code !=0){
            throw new BusinessException("授权失败,请联系我们");
        }
        String accessToken = qqResult.access_token;
        log.info("获取 appId - >{} openId start",appId);

        Map<String,Object> paramOpenIdMap = new HashMap<>(2);
        paramOpenIdMap.put("access_token",accessToken);
        paramOpenIdMap.put("fmt",FORMAT_JSON);
        String openIdResult = HttpClientUtil.get(QQ_URL+"/oauth2.0/me", paramOpenIdMap, null, 3000, "utf8", 3, true);
        log.info("获取 qq appId - >{} openId result {} ",appId,openIdResult);
        QQResult qqOpenIdResult = JSON.parseObject(openIdResult, QQResult.class);
        if(qqOpenIdResult.code!=0){
            throw new BusinessException("授权失败,请联系我们");
        }
        log.info("获取 qq appId - >{} openId - {}  userInfo start",appId,qqOpenIdResult.openid);
        Map<String,Object> paramUserInfoMap = new HashMap<>(4);
        paramUserInfoMap.put("access_token",accessToken);
        paramUserInfoMap.put("oauth_consumer_key",appId);
        paramUserInfoMap.put("openid",qqOpenIdResult.openid);
        paramUserInfoMap.put("fmt",FORMAT_JSON);
        String userInfoResult = HttpClientUtil.get(QQ_URL+"/user/get_user_info", paramUserInfoMap, null, 3000, "utf8", 3, true);
        log.info("获取 qq appId - >{} openId - {}  userInfo result {}",appId,qqOpenIdResult.openid,userInfoResult);
        QQUserInfoResult qqUserInfoResult = JSON.parseObject(userInfoResult, QQUserInfoResult.class);
        if(qqUserInfoResult.ret !=0){
            throw new BusinessException("授权失败,请联系我们");
        }
        qqUserInfoResult.setOpenid(qqOpenIdResult.openid);
        return qqUserInfoResult;
    }

    public String authorizeCode(WechatH5CodeReqVO req){
        log.info(" start Authorization Code");
        try {
            String activityThemeColor = getActivityColor(req.getActivityId());
            String redirectUri ="";
            if(StringUtils.isNotBlank(req.getExtension())){
                redirectUri = URLEncoder.encode(platformConfigService.getQQBizFrontDomain() + "/h5/index.html?#/pages/user-login" +
                        "?activityId=" + req.getActivityId() + "&appId=" + req.getAppId() + "&type=" + req.getType() +
                        "&theme=" + activityThemeColor+"&platform=qq-h5&authorizeMode=qq"+"&extension="+req.getExtension(), "UTF-8");
            }else{
                redirectUri = URLEncoder.encode(platformConfigService.getQQBizFrontDomain() + "/h5/index.html?#/pages/user-login" +
                        "?activityId=" + req.getActivityId() + "&appId=" + req.getAppId() + "&type=" + req.getType() +
                        "&theme=" + activityThemeColor+"&platform=qq-h5&authorizeMode=qq", "UTF-8");
            }

            String authorizeUrl = String.format(AUTHORIZE_URL, req.getAppId(), redirectUri);
            log.info(" end Authorization Code result - > {}",authorizeUrl);
            return authorizeUrl;
        } catch (Exception e) {
            log.error(" qq Authorization Code 获取解码错误:{}", e);
            return "";
        }

    }

    private String getActivityColor(String activityId){
        Query query = new Query().addCriteria(Criteria.where("id").is(activityId));
        ActivityInfo activityInfo = mongoTemplate.findOne(query, ActivityInfo.class);
        if (Objects.isNull(activityInfo) || StringUtils.isBlank(activityInfo.getThemeColor())) {
            log.error(":>>> 活动:{} 不存在,或颜色配置:{}", activityId, activityInfo.getThemeColor());
            throw new com.youlu.campus.base.exception.BusinessException("活动不存在,或颜色配置错误");
        }
        return activityInfo.getThemeColor();
    }

}
